package com.mnsq.user.service.impl;

import com.mnsq.common.bean.enums.TimeEnum;
import com.mnsq.common.service.RedisServer;
import com.mnsq.common.tools.jpa.JpaExample;
import com.mnsq.common.tools.tool.GenerateKey;
import com.mnsq.user.bean.base.ThreadLocalInfo;
import com.mnsq.user.bean.condition.UserOperationCondition;
import com.mnsq.user.bean.dto.LoginInfo;
import com.mnsq.user.bean.entity.UserSuggest;
import com.mnsq.user.bean.entity.UserVolatileInfo;
import com.mnsq.user.dao.UserInfoRepository;
import com.mnsq.user.dao.UserSuggestRepository;
import com.mnsq.user.service.UserOperationService;
import com.vwkit.common.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Administrator
 * @date 2019/4/21 0021
 */
@Service
public class UserOperationServiceImpl implements UserOperationService {

    @Autowired
    private UserSuggestRepository userSuggestRepository;
    @Autowired
    private RedisServer redisServer;
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Override
    public Result save(UserOperationCondition userOperationCondition) {
        LoginInfo loginInfo = ThreadLocalInfo.LOGIN_INFO.get();
        String key = GenerateKey.readableKey("", loginInfo.getUserId());
        if (redisServer.hasKey(key)) {
            return Result.fail("抱歉，24小时内只可提交一次建议。");
        }
        redisServer.setValue(key, "1", TimeEnum.HOUR_TWENTY_FOUR.time);
        UserSuggest userSuggest = new UserSuggest();
        userSuggest.setUserId(loginInfo.getUserId());
        userSuggest.setContent(userOperationCondition.getContent());
        userSuggestRepository.saveAndFlush(userSuggest);
        return Result.success(null);
    }

    @Override
//    @AutoCache(value = 12L, cacheType = AutoCache.CacheType.HOURS, cls = Result.class, prefix = "userCounts")
    public Result userCounts(Long userId) {
        UserVolatileInfo userVolatileInfo = new UserVolatileInfo();
        userVolatileInfo.setUserId(userId);
        Optional one = userInfoRepository.findOne(JpaExample.getInstance().getExample(userVolatileInfo, new UserVolatileInfo()));
        return Result.success(one.orElse(null));
    }
}
